
var bg = chrome.extension.getBackgroundPage();

var content_list = [];
var wechat_checkST1;

$(document).ready(function () {
    init_tab();

    checktoken();

    $("#loginbutton").click(function () {
        login();
    });
    $("#regiserbutton").click(function () {
        $("#login_modal").hide();
        $("#register_modal").show();
    });
    $("#re_regiserbutton").click(function () {
        register();
    });
    $("#forgetbutton").click(function () {
        $("#login_modal").hide();
        $("#forget_modal").show();
    });
    $("#seccodebutton").click(function () {
        mailseccode();
    });
    $("#re_forgetbutton").click(function () {
        updatepassword();
    });
    $("#follow_q_tab").click(function () {
        change_tab(this);
    });
    $("#collect_content_tab").click(function () {
        change_tab(this);
    });
    $("#zcpf_tab").click(function () {
        change_tab(this);
    });
    $("#cp_tab").click(function () {
        change_tab(this);
    });
    $("#vip_tab").click(function () {
        change_tab(this);
        find_pay_info();
    });
    $("#help_button").click(function(){
        window.open("https://shimo.im/docs/TqdRH8R938jyHT6d");
    });
    $("#keyword_ser").click(function () {
        keyword_ser();
    });
    $("#multi_key_ser").click(function () {
        multi_key_ser();
    });
    // $("#follow_q_button").click(function(){
    //     follow_q_add();
    // });
    $("#mul_ser_change").click(function () {
        $("#single_key").hide();
        $("#multi_key").show();
    });
    $("#single_ser_change").click(function () {
        $("#single_key").show();
        $("#multi_key").hide();
    });
    $("#check_button").click(async function () {
        $(this).attr("disabled", true);
        $(this).text("请等待，不要关闭插件...");
        await getarticle_list();
        $(this).attr("disabled", false);
        $(this).text("一键检查失效连接");
    });
    $("#multi_history_srot").click(function(){
        multi_history_srot();
    });
    $("#cp_check_button").click(async function () {
        $(this).attr("disabled", true);
        await check_cp();
    });

    

});

function compare(pro) { 
    return function (obj1, obj2) { 
        var val1 = obj1[pro]; 
        var val2 = obj2[pro]; 
        if (val1 < val2 ) { //正序
            return 1; 
        } else if (val1 > val2 ) { 
            return -1; 
        } else { 
            return 0; 
        } 
    } 
}

function multi_history_srot(){
    let history_qry = {
        pageSize: 10,
        pageNo: 1,
        orderby: "id",
        ordertype: "desc"
    };
    bg.get_history_list(history_qry, function (res) {
        console.log(res);
        if (res.code != 0) {
            return
        }
        let list = res.data;

        for (var i = 0; i < list.length; i++) {
            var res = $.parseJSON(list[i].json);
            list[i].pf = res.pf;
        }

        list.sort(compare("pf")); 
        show_multi_ser_data(list);
    })
}

function multi_split(str) {
    var temp = str.split(/[\n,;]/g);
    for (var i = 0; i < temp.length; i++) {
        if (temp[i] == "") {
            temp.splice(i, 1);
            //删除数组索引位置应保持不变
            i--;
        }
    }
    console.log(temp);
    return temp;
}

async function getarticle_list() {
    var res = await bg.post_check_mcn();
    // console.log(res);
    if (res.code == 0) {
        write_article_dom(res.article_list_mcn);
        write_answer_dom(res.answer_list_mcn);
        $("#check_mcn_message").text(res.nikename+" 帐号已检查完毕");
    }else{
        $("#check_mcn_message").text(res.msg);
    }
}

async function init_self_list_mcn() {
    var res = bg.self_list_mcn;
    // console.log(res);
    if(res==null){
        return
    }

    if (res.code == 0) {
        write_article_dom(res.article_list_mcn);
        write_answer_dom(res.answer_list_mcn);
        $("#check_mcn_message").text(res.nikename+" 帐号已检查完毕");
    }
}

async function write_answer_dom(list){
    $(".q_answer_div").remove();
    var tmp = "<div class=\"q_answer_div\"><div class=\"q_title\"></div><div><span class=\"q_type\"></span><span class=\"q_mcn_font\">内含</span><span class=\"q_mcn_all q_mcn_num\"></span><span class=\"q_mcn_font\">件商品</span><span class=\"q_float_right\"style=\"display: none;\"><span class=\"q_mcn_font\">失效</span><span class=\"q_mcn_unwork q_mcn_num\"></span><span class=\"q_mcn_font\">件</span><span class=\"q_arc_mcn_show btn btn-xs btn-default\">显示</span></span></div><div class=\"art_mcn_list\" style=\"display:none;margin-top:10px\"></div><hr/></div>";
    for (var i = 0; i < list.length; i++) {
        var obj = list[i];
        var tmpdiv = $(tmp);
        tmpdiv.find(".q_title:first").text(obj.title);
        var type = "回答";
        tmpdiv.attr("itemid", obj.id);
        tmpdiv.find(".q_type:first").text(type);
        tmpdiv.find(".q_mcn_all:first").text(obj.mcn_num);
        tmpdiv.find(".q_title:first").attr("href", "https://www.zhihu.com/question/"+obj.question_id+"/answer/"+obj.id);
        
        var art_mcn_list = tmpdiv.find(".art_mcn_list:first");
        for (var k = 0; k < obj.mcn_list.length; k++) {
            var mcn = obj.mcn_list[k];
            if (mcn.mcn_isvail == null || mcn.mcn_isvail == 0) {
                
                var tmp_mcn_t = "<div class=\"RichText-MCNLinkCardContainer\"><div class=\"MCNLinkCard\"data-draft-node=\"block\"data-draft-type=\"mcn-link-card\"data-mcn-id=\"\"data-za-not-track-link=\"true\"href=\"\"target=\"_blank\"rel=\"noopener noreferrer\"style=\"margin-bottom:10px\"><div class=\"MCNLinkCard-card\"><div class=\"MCNLinkCard-cardContainer\"><div class=\"MCNLinkCard-imageContainer MCNLinkCard-imageContainer--square\"><img class=\"MCNLinkCard-image\"src=\"\"alt=\"\"></div><div class=\"MCNLinkCard-info\"><div class=\"MCNLinkCard-title\"><div class=\"MCNLinkCard-titleText\"></div><div class=\"MCNLinkCard-tagList\"><div class=\"MCNLinkCard-tag MCNLinkCard-tag--source\"></div></div></div><div class=\"MCNLinkCard-tool\"><div class=\"MCNLinkCard-toolLeft\"><div class=\"MCNLinkCard-price\"><span></span></div></div><div class=\"MCNLinkCard-button\"role=\"button\">去购买<span style=\"display: inline-flex; align-items: center;\">&#8203;<svg class=\"Zi Zi--ArrowRight\"fill=\"currentColor\"viewBox=\"0 0 24 24\"width=\"17\"height=\"17\"><path d=\"M9.218 16.78a.737.737 0 0 0 1.052 0l4.512-4.249a.758.758 0 0 0 0-1.063L10.27 7.22a.737.737 0 0 0-1.052 0 .759.759 0 0 0-.001 1.063L13 12l-3.782 3.716a.758.758 0 0 0 0 1.063z\"fill-rule=\"evenodd\"></path></svg></span></div></div></div></div></div></div></div>";
                var tmp_mcn = $(tmp_mcn_t);
                tmp_mcn.find(".MCNLinkCard:first").attr("data-mcn-id", mcn.id);
                tmp_mcn.find(".MCNLinkCard:first").attr("ata-mcn-skuid", mcn.skuid);
                tmp_mcn.find(".MCNLinkCard:first").attr("href", mcn.url);
                tmp_mcn.find(".MCNLinkCard-image:first").attr("src", mcn.img_url);
                tmp_mcn.find(".MCNLinkCard-titleText:first").text(mcn.title);
                tmp_mcn.find(".MCNLinkCard-tag:first").text(mcn.source);
                tmp_mcn.find(".MCNLinkCard-price:first").text(mcn.price_text);
                tmp_mcn.find(".MCNLinkCard:first")[0].addEventListener('click', function () {
                    var mcn_href = $(this).attr("href");
                    window.open(mcn_href);
                });
                
                art_mcn_list.append(tmp_mcn);
            }
        }
        tmpdiv.find(".q_mcn_unwork:first").text(obj.mcn_list.length);
        tmpdiv.find(".q_float_right:first").show();

        tmpdiv.find(".q_title:first")[0].addEventListener('click', function () {
            window.open($(this).attr("href"));
        });
        tmpdiv.find(".q_arc_mcn_show:first")[0].addEventListener('click', function () {
            var art_mcn_list = $(this).parent().parent().parent().find(".art_mcn_list:first");
            if ($(this).text() == "显示") {
                art_mcn_list.show();
                $(this).text("隐藏");
            } else {
                art_mcn_list.hide();
                $(this).text("显示");
            }
        });
        $("#answer_list").append(tmpdiv);
    }
}

async function write_article_dom(list){
    $(".q_article_div").remove();
    var tmp = "<div class=\"q_article_div\"><div class=\"q_title\"></div><div><span class=\"q_type\"></span><span class=\"q_mcn_font\">内含</span><span class=\"q_mcn_all q_mcn_num\"></span><span class=\"q_mcn_font\">件商品</span><span class=\"q_float_right\"style=\"display: none;\"><span class=\"q_mcn_font\">失效</span><span class=\"q_mcn_unwork q_mcn_num\"></span><span class=\"q_mcn_font\">件</span><span class=\"q_arc_mcn_show btn btn-xs btn-default\">显示</span></span></div><div class=\"art_mcn_list\" style=\"display:none;margin-top:10px\"></div><hr/></div>";
    for (var i = 0; i < list.length; i++) {
        var obj = list[i];
        var tmpdiv = $(tmp);
        tmpdiv.find(".q_title:first").text(obj.title);
        var type = "文章";
        tmpdiv.attr("itemid", obj.id);
        tmpdiv.find(".q_type:first").text(type);
        tmpdiv.find(".q_mcn_all:first").text(obj.mcn_num);
        tmpdiv.find(".q_title:first").attr("href", "https://zhuanlan.zhihu.com/p/"+obj.id);
        
        var art_mcn_list = tmpdiv.find(".art_mcn_list:first");
        for (var k = 0; k < obj.mcn_list.length; k++) {
            var mcn = obj.mcn_list[k];
            if (mcn.mcn_isvail == null || mcn.mcn_isvail == 0) {
                
                var tmp_mcn_t = "<div class=\"RichText-MCNLinkCardContainer\"><div class=\"MCNLinkCard\"data-draft-node=\"block\"data-draft-type=\"mcn-link-card\"data-mcn-id=\"\"data-za-not-track-link=\"true\"href=\"\"target=\"_blank\"rel=\"noopener noreferrer\"style=\"margin-bottom:10px\"><div class=\"MCNLinkCard-card\"><div class=\"MCNLinkCard-cardContainer\"><div class=\"MCNLinkCard-imageContainer MCNLinkCard-imageContainer--square\"><img class=\"MCNLinkCard-image\"src=\"\"alt=\"\"></div><div class=\"MCNLinkCard-info\"><div class=\"MCNLinkCard-title\"><div class=\"MCNLinkCard-titleText\"></div><div class=\"MCNLinkCard-tagList\"><div class=\"MCNLinkCard-tag MCNLinkCard-tag--source\"></div></div></div><div class=\"MCNLinkCard-tool\"><div class=\"MCNLinkCard-toolLeft\"><div class=\"MCNLinkCard-price\"><span></span></div></div><div class=\"MCNLinkCard-button\"role=\"button\">去购买<span style=\"display: inline-flex; align-items: center;\">&#8203;<svg class=\"Zi Zi--ArrowRight\"fill=\"currentColor\"viewBox=\"0 0 24 24\"width=\"17\"height=\"17\"><path d=\"M9.218 16.78a.737.737 0 0 0 1.052 0l4.512-4.249a.758.758 0 0 0 0-1.063L10.27 7.22a.737.737 0 0 0-1.052 0 .759.759 0 0 0-.001 1.063L13 12l-3.782 3.716a.758.758 0 0 0 0 1.063z\"fill-rule=\"evenodd\"></path></svg></span></div></div></div></div></div></div></div>";
                var tmp_mcn = $(tmp_mcn_t);
                tmp_mcn.find(".MCNLinkCard:first").attr("data-mcn-id", mcn.id);
                tmp_mcn.find(".MCNLinkCard:first").attr("ata-mcn-skuid", mcn.skuid);
                tmp_mcn.find(".MCNLinkCard:first").attr("href", mcn.url);
                tmp_mcn.find(".MCNLinkCard-image:first").attr("src", mcn.img_url);
                tmp_mcn.find(".MCNLinkCard-titleText:first").text(mcn.title);
                tmp_mcn.find(".MCNLinkCard-tag:first").text(mcn.source);
                tmp_mcn.find(".MCNLinkCard-price:first").text(mcn.price_text);
                tmp_mcn.find(".MCNLinkCard:first")[0].addEventListener('click', function () {
                    var mcn_href = $(this).attr("href");
                    window.open(mcn_href);
                });
                
                art_mcn_list.append(tmp_mcn);
            }
        }
        tmpdiv.find(".q_mcn_unwork:first").text(obj.mcn_list.length);
        tmpdiv.find(".q_float_right:first").show();

        tmpdiv.find(".q_title:first")[0].addEventListener('click', function () {
            window.open($(this).attr("href"));
        });
        tmpdiv.find(".q_arc_mcn_show:first")[0].addEventListener('click', function () {
            var art_mcn_list = $(this).parent().parent().parent().find(".art_mcn_list:first");
            if ($(this).text() == "显示") {
                art_mcn_list.show();
                $(this).text("隐藏");
            } else {
                art_mcn_list.hide();
                $(this).text("显示");
            }
        });
        $("#article_list").append(tmpdiv);
    }
}

async function checktoken() {
    var token = await bg.getStoreTxt("token");
    if (token == null) {
        $("#content").hide();
        $("#login_modal").show();
        return;
    }

    bg.checktoken(function (res) {
        if (res.code == 0) {
            bg.flashbgtoken();

            open_init_show(res);
        } else {
            chrome.storage.local.remove('token', function () { });
            bg.flashbgtoken();
        }
    });
}

async function register() {

    var mail = $("#re_mail").val();
    var pwd = $("#re_pwd").val();
    var pwd_se = $("#re_pwd_se").val();
    if (mail.length <= 0) {
        $("#re_note").text("邮箱不能为空");
        return;
    }
    if (pwd.length <= 0 || pwd_se.length <= 0) {
        $("#re_note").text("密码不能为空");
        return;
    }
    if (!checkemail(mail)) {
        $("#re_note").text("邮箱格式错误");
        return;
    }
    if (pwd_se != pwd) {
        $("#re_note").text("两次密码输入不一致");
        return;
    }
    $("#re_regiserbutton").attr("disabled", true);

    bg.register(mail, pwd, async function (res) {
        $("#re_note").text(res.msg);
    });
}

async function mailseccode(){
    var mail = $("#for_mail").val();
    if (mail.length <= 0) {
        $("#for_note").text("邮箱不能为空");
        return;
    }

    $("#seccodebutton").attr("disabled", true);

    bg.mailseccode(mail, async function (res) {
        $("#for_note").text(res.msg);
        if(res.code != 5){
            $("#seccodebutton").attr("disabled", false);
        }
    });
}

async function updatepassword(){
    var mail = $("#for_mail").val();
    var pwd = $("#for_pwd").val();
    var code = $("#seccode").val();
    if (mail.length <= 0) {
        $("#for_note").text("邮箱不能为空");
        return;
    }
    if (pwd.length <= 0) {
        $("#for_note").text("密码不能为空");
        return;
    }
    if (code.length <= 0) {
        $("#for_note").text("验证码不能为空");
        return;
    }

    $("#re_forgetbutton").attr("disabled", true);

    bg.updatepass(mail,pwd,code ,async function (res) {
        $("#for_note").text(res.msg);
        if(res.code != 0){
            $("#re_forgetbutton").attr("disabled", false);
        }
    });
}

function login() {
    var mail = $("#mail").val();
    var pwd = $("#pwd").val();
    if (mail.length <= 0) {
        $("#note").text("邮箱不能为空");
        return;
    }
    if (pwd.length <= 0) {
        $("#note").text("密码不能为空");
        return;
    }
    if (!checkemail(mail)) {
        $("#note").text("邮箱格式错误");
        return;
    }
    $("#note").text("登陆中...");
    bg.login(mail, pwd, async function (res) {
        if (res.code != 0) {
            $("#note").text(res.msg);
        } else {
            var token = res.data.token;
            chrome.storage.local.set({ 'token': token }, function () { });
            await bg.flashbgtoken();

            open_init_show(res);
        }
    });
}



function open_init_show(res) {
    $("#login_modal").hide();
    $("#content").show();

    init_show_ser_data();
    init_self_list_mcn();
    init_follow();

    if (res.data.is_vip != null) {
        $("#check_button").attr("disabled", false);
        $("#mul_ser_change").attr("disabled", false);
        $("#cp_check_button").attr("disabled", false);
        $("#lasttime").children("span").text(formatDateTime(res.data.lasttime));
    } else {
        $("#check_button").text("检查失效连接（仅支持VIP）");
        $("#cp_check_button").text("查重（仅支持VIP）");
        $("#mul_ser_change").text("批量及历史（仅支持VIP）");
        $("#lasttime").hide();
    }
}

function checkemail(val) {
    var email = val;
    var reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
    if (reg.test(email)) {
        return true;
    } else {
        return false;
    }
}

function getLeftTime(leftTime) {
    if (!isNaN(leftTime)) {
        if (leftTime <= 0) {
            return "00:00:00";
        } else {
            var date = new Date(null);
            date.setMilliseconds(leftTime);
            var result = date.toISOString().substr(11, 8);
            return result;
        }
    }
}

/**
 * 日期格式化
 * @param inputTime
 * @returns {string}
 */
function formatDateTime(inputTime) {
    var date = new Date(inputTime);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
}


/**
 * 日期格式化
 * @param inputTime
 * @returns {string}
 */
function formatDate(inputTime) {
    var date = new Date(inputTime);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    return y + '-' + m + '-' + d;
}

function rgb2hex(rgb) {
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

function change_tab(e) {
    $(e).parent().parent().find("li").removeClass("active");
    $(e).parent().addClass("active");

    var id = $(e).attr("id");
    if (id == null) {
        return;
    }
    var tab_id = id.substr(0, id.length - 4);
    $("#myTabContent").find(".tab-pane").removeClass("in active");
    $("#" + tab_id).addClass("in active");

    bg.popup_active_tab = id;
    
}

function init_tab(){
    var id = bg.popup_active_tab;
    if(id!=null){
        $("#" + id).parent().parent().find("li").removeClass("active");
        $("#" + id).parent().addClass("active");

        var tab_id = id.substr(0, id.length - 4);
        $("#myTabContent").find(".tab-pane").removeClass("in active");
        $("#" + tab_id).addClass("in active");
        
    }
}

async function init_show_ser_data() {
    var res = await bg.read("ser_key");
    console.log(res);
    if (bg.getser_key_flag() == 1) {
        $("#keyword_ser").attr("disabled", true);
        $("#keyword_ser").text("请等待...(窗口可关闭)");
    } else {
        if (res.ser_key != null) {
            show_ser_data(res.ser_key);
        }
    }

    if (bg.getmulti_ser_key_flag() == 1) {
        $("#multi_key_ser").attr("disabled", true);
        $("#multi_key_ser").text("请等待...(窗口可关闭)");
    }
    let history_qry = {
        pageSize: 10,
        pageNo: 1,
        orderby: "id",
        ordertype: "desc"
    };
    bg.get_history_list(history_qry, function (res) {
        console.log(res);
        if (res.code != 0) {
            return
        }
        let list = res.data;
        show_multi_ser_data(list);
    })

    var cp_res = await bg.read("checkrp");
    console.log(cp_res);
    if (cp_res.checkrp != null) {
        show_checkcp_res(cp_res.checkrp);
    }
}

async function keyword_ser() {

    var key = $("#keyword").val();
    if (key == null || key.trim().length == 0) {
        return
    }
    $("#keyword_ser").attr("disabled", true);
    $("#keyword_ser").text("请等待...(窗口可关闭)");
    $("#multi_key_ser").attr("disabled", true);
    $("#multi_key_ser").text("请等待...(窗口可关闭)");

    await bg.ser_key(key, function (res) {
        show_ser_data(res);

        $("#keyword_ser").attr("disabled", false);
        $("#keyword_ser").text("查询种草评分");
        $("#multi_key_ser").attr("disabled", false);
        $("#multi_key_ser").text("批量查询种草评分");
    });
}

async function multi_key_ser() {
    var key = $("#multi_keyword").val();
    if (key == null || key.trim().length == 0) {
        return
    }
    console.log("start_multi_ser");
    var list = multi_split(key);

    if (list.length > 5) {
        list = list.slice(0, 5);
    }

    console.log(list);
    $("#multi_key_ser").attr("disabled", true);
    $("#multi_key_ser").text("请等待...(窗口可关闭)");
    $("#keyword_ser").attr("disabled", true);
    $("#keyword_ser").text("请等待...(窗口可关闭)");
    await bg.multi_ser_key(list, function (obj) {
        $("#multi_key_ser").attr("disabled", false);
        $("#multi_key_ser").text("批量查询种草评分");
        $("#keyword_ser").attr("disabled", false);
        $("#keyword_ser").text("查询种草评分");
        let history_qry = {
            pageSize: 10,
            pageNo: 1,
            orderby: "id",
            ordertype: "desc"
        };
        bg.get_history_list(history_qry, function (res) {
            console.log(res);
            if (res.code != 0) {
                return
            }
            let list = res.data;
            show_multi_ser_data(list);
        })
    });

}

async function show_multi_ser_data(obj) {
    // var obj = await bg.get_history();
    $("#multi_ques_body").find("tr").remove();

    for (var i = 0; i < obj.length; i++) {
        var res = $.parseJSON(obj[i].json);

        var tmp_tr = "<tr><td></td><td></td><td style=\"font-weight: bold;\"></td><td><span class=\"glyphicon glyphicon-remove\"></span></td></tr>";
        var tmp = $(tmp_tr);
        tmp.find("td:first").text(res.key);
        tmp.find("td:first").addClass("q_cursor");
        tmp.find("td:first").attr("sort", i);
        tmp.find("td:first").click(function () {

            var tmpres = $.parseJSON(obj[$(this).attr("sort")].json);

            chrome.storage.local.set({'ser_key': tmpres}, function() {});
            
            show_ser_data(tmpres);
            $("#single_key").show();
            $("#multi_key").hide();
        })
        tmp.find("td:eq(1)").text(res.pf.toFixed(2));
        tmp.find("td:eq(2)").text(res.data[0].title);
        tmp.find("td:eq(2)").attr("q_id", res.data[0].id);
        tmp.find("td:eq(2)").addClass("q_cursor");
        tmp.find("td:eq(2)").click(function () {
            window.open("https://www.zhihu.com/question/" + $(this).attr("q_id"));
        });
        tmp.find("td:last").attr("his_id", obj[i].id);
        tmp.find("td:last").addClass("q_cursor");
        tmp.find("td:last").click(function () {
            bg.remove_his($(this).attr("his_id"),function(r){
                if(r.code!=0){
                    return;
                }
                let history_qry = {
                    pageSize: 10,
                    pageNo: 1,
                    orderby: "id",
                    ordertype: "desc"
                };
                bg.get_history_list(history_qry, function (res) {
                    console.log(res);
                    if (res.code != 0) {
                        return
                    }
                    let list = res.data;
                    show_multi_ser_data(list);
                })
            });
        });
        $("#multi_ques_body").append(tmp);
    }
}

function show_ser_data(res) {
    console.log(res);
    $("#keyword").val(res.key);
    $("#question_num").text(res.question_num);
    $("#answer_num").text(res.answer_num_sum);
    $("#mcn_num").text((res.mcn_num_sum / res.answer_id_length).toFixed(2));
    $("#answer_yes").text((res.answer_yes / res.answer_id_length).toFixed(2));
    $("#follower_sum").text((res.follower_sum / 10000).toFixed(2) + "万");
    $("#visit_sum").text((res.visit_sum / 10000).toFixed(2) + "万");
    // var pj_yes = res.answer_yes==0?0.01:res.answer_yes/res.answer_id_length;
    // var pj_mcn = res.mcn_num_sum==0?0.01:res.mcn_num_sum/res.answer_id_length;
    // var pf = Math.log(res.visit_sum/res.answer_num_sum/5000)*100+Math.log(1000/pj_yes)*50+Math.log(1/pj_mcn)*100;
    $("#pf_caption").text(res.pf.toFixed(2));

    var question_list = res.data;

    $("#ques_body").find("tr").remove();
    for (var i = 0; i < question_list.length; i++) {

        var q = question_list[i];
        console.log(q.pingfen);
        var tmp_tr = "<tr><td></td><td style=\"vertical-align: middle;font-weight: bold;\"></td></tr>";
        var tmp = $(tmp_tr);
        tmp.find("td:last").text(q.title); 
        if(q.baidu){
            tmp.find("td:last").append('<embed src="../image/baidu.svg" width="18" height="18" type="image/svg+xml"/>');
        }
        
        tmp.find("td:first").text(q.pingfen.toFixed(2));
        tmp.find("td:last").attr("q_id", q.id);
        tmp.find("td:last").addClass("q_cursor");
        
        tmp.find("td:last").click(function () {
            window.open("https://www.zhihu.com/question/" + $(this).attr("q_id"));
        });
        $("#ques_body").append(tmp);
    }
}

async function check_cp() {
    var text = $("#cp_text").val().replace(new RegExp(" ","gm"),"");
    text = text.replace(/(\n[\s\t]*\r*\n)/g, '\n').replace(/<\s?img[^>]*>/g,"\n").replace(/^[\n\r\n\t]*|[\n\r\n\t]*$/g, '');
    await bg.checkrp(text, function (res) {
        show_checkcp_res(res)
    });
}

function show_checkcp_res(res) {
    if(res.copy==1){
        $("#cp_text").val(res.text);
        return;
    }
    console.log(res);
    let list = res.list;
    if (res.code != 0) {
        $("#cp_check_res").text("失败");
        return;
    }

    $("#cp_text").val(res.text);

    $("#cp_check_table").find("tr").remove();
    $("#cp_check_res").text("成功");
    $("#show_text").text(res.text);

    var serious_reg = "";
    var secondary_reg = "";

    for (var i = 0; i < list.length; i++) {
        var cq_res = list[i];
        var tmp_tr = "<tr><td></td><td style=\"font-weight: bold;\"></td><td></td><td></td></tr>";
        var tmp = $(tmp_tr);
        tmp.find("td:first").text(cq_res.ParagraphPosition);
        var cd = "";
        
        tmp.find("td:eq(2)").text(cq_res.Content);
        tmp.find("td:last").text(cq_res.Content.length);
        if (cq_res.OriginalValue == "serious") {
            cd = "严重";
            tmp.find("td:first").css("color", "red");
            tmp.find("td:eq(1)").css("color", "red");
            tmp.find("td:eq(2)").css("color", "red");
            tmp.find("td:last").css("color", "red");
            serious_reg = serious_reg + regexcontent(cq_res.Content) + "|";
        } else if (cq_res.OriginalValue == "secondary") {
            cd = "中等";
            secondary_reg = secondary_reg + regexcontent(cq_res.Content) + "|";
        }
        tmp.find("td:eq(1)").text(cd);
        
        $("#cp_check_table").append(tmp);
    }

    if (secondary_reg.length > 0) {
        secondary_reg = secondary_reg.substring(0, secondary_reg.length - 1);
    }

    if (serious_reg.length > 0) {
        serious_reg = serious_reg.substring(0, serious_reg.length - 1);
    }

    console.log(secondary_reg);
    console.log(serious_reg);
    var html = $("#show_text").html();
    if (secondary_reg.length > 0) {
        html = highlight(html, { color: '#ffe951', keys: secondary_reg });
    }
    if (serious_reg.length > 0) {
        html = highlight(html, { color: '#ff9191', keys: serious_reg });
    }
    $("#show_text").html(html);
    $("#cp_check_button").attr("disabled", false);
}

function regexcontent(strindex){
    var specialStr = ["\\","*", ".", "?", "+", "$", "^", "[", "]", "{", "}", "|",  "(", ")", "/", "%"]; 
    console.log(strindex);
    $.each(specialStr, function(i, item) {
        if(strindex.indexOf(item) != -1) {
            strindex = strindex.replace(new RegExp("\\" + item, 'g'), "\\" + item);
        }
    })
    console.log(strindex);
    return strindex;
}

function highlight(str, params) {
    console.log(params.keys);
    var reg = new RegExp(("(" + params.keys + ")"), "gm");
    var color = params.color || '#f00';
    var weight = 'bold';
    var replace = '<span style="background-color:' + color + ';font-weight: ' + weight + ';">$1</span>';
    return str.replace(reg, replace);
}

function find_pay_info() {
    bg.pay_info(function (res) {
        if (res.code == 0) {
            let data = res.data;
            if (data.length == 0) {
                return
            }

            $("#pay_buttons").find("button").remove();
            var width = 100 / data.length - 2;
            for (var i = 0; i < data.length; i++) {
                var tmp = data[i];
                var button = $(tmp.text);
                console.log(button);

                button.attr("qi_type", tmp.type);
                button.click(function () {
                    $("#pay_buttons").find("button").attr("disabled", true);
                    bg.pay_getcode($(this).attr("qi_type"), function (res) {
                        console.log(res);
                        if (res.code == 0) {
                            var url = res.data.url;
                            $("#pay_code").attr("src", url);
                            $("#pay_code").show();
                            $("#paymsg").show();
                            wechat_checkST1 = setInterval(function(){
                                check_order(res.data.id);
                            }, 2000);
                        } else {
                            $("#paymsg").text("生成支付二维码失败");
                            $("#paymsg").show();
                        }
                    });
                })
                $("#pay_buttons").append(button);
                button.css("width", width + "%");
                button.css("margin", "3px");
            }
        }
    })
}

function hide_wx() {
    clearTimeout(wechat_checkST1);
    $("#paymsg").text("支付成功！");
    $("#pay_code").hide();
}

function check_order(order_id) {
    bg.check_pay_status(order_id,function(res){
        if(res.code==0 && res.data){
            hide_wx();
        }
    })
}

async function init_follow(){
    var follows = await bg.read("follow_q");

    console.log(follows);

    if(follows.follow_q==null){
        return;
    }

    var res = follows.follow_q;

    console.log(res);

    var tmp =$('<tr><td style="font-weight: bold;">123123132</td><td><span style="color:red;" class="q_cursor glyphicon glyphicon-remove"></span></td></tr>');
    tmp.find("td:first").text(res.title);
    tmp.find("span:first").attr("follow_question_id",res.id);
    tmp.find("span:first").click(function(){
        chrome.storage.local.remove('follow_q', function() {});
        $(this).parent().parent().remove();
    })
    
    $("#follow_body").append(tmp);
}

function follow_q_add(){
    var url = $("#question_link").val();
    $("#follow_tips").text("");

    var reg_str = /www\.zhihu\.com\/question\/(\d+)/;

    if(!reg_str.test(url)){
        $("#follow_tips").text("链接格式不对");
        return;
    }

    var mat = url.match(reg_str);

    if(mat.length!=2){
        $("#follow_tips").text("链接格式不对");
        return;
    }

    var id = mat[1];

    bg.follow_q_start(id,function(res){
        console.log(res);
        if(res==0){
            $("#follow_tips").text("监控问题数据已达上限");
        }else if(res==1){
            $("#follow_tips").text("问题查询不到或查询失败");
        }else{
            var tmp =$('<tr><td style="font-weight: bold;">123123132</td><td><span style="color:red;" class="q_cursor glyphicon glyphicon-remove"></span></td></tr>');
            tmp.find("td:first").text(res.title);
            tmp.find("span:first").attr("follow_question_id",res.id);
            tmp.find("span:first").click(function(){
                chrome.storage.local.remove('follow_q', function() {});
                $(this).parent().parent().remove();
            })
            $("#follow_body").append(tmp);
        }
    })
}